import { useEffect, useState } from 'react';
import { useLanguage } from '../contexts/LanguageContext';
import ReactMarkdown from 'react-markdown';

const TermsOfService = () => {
  const { language } = useLanguage();
  const [content, setContent] = useState('');
  const [headings, setHeadings] = useState<{ id: string; text: string; level: number }[]>([]);

  useEffect(() => {
    const loadContent = async () => {
      try {
        const response = await fetch(`/legal/terms-of-service${language === 'zh-CN' ? '.zh-CN' : ''}.md`);
        if (!response.ok) {
          throw new Error(`Failed to fetch: ${response.status}`);
        }
        const text = await response.text();
        console.log('Loaded content length:', text.length);
        setContent(text);
        
        // Extract headings for table of contents using regex (same as app version)
        const headingRegex = /^(#{1,6})\s+(.+)$/gm;
        const extractedHeadings: { id: string; text: string; level: number }[] = [];
        let match;

        while ((match = headingRegex.exec(text)) !== null) {
          const level = match[1].length;
          const headingText = match[2].replace(/\[([^\]]+)\]\([^)]+\)/g, '$1'); // Remove markdown links
          const id = headingText
            .toLowerCase()
            .replace(/[^\w\s-]/g, '')
            .replace(/\s+/g, '-');
          
          extractedHeadings.push({ id, text: headingText, level });
        }
        
        console.log('Extracted headings:', extractedHeadings);
        setHeadings(extractedHeadings);
      } catch (error) {
        console.error('Error loading terms of service:', error);
      }
    };

    loadContent();
  }, [language]);

  const scrollToHeading = (id: string) => {
    const element = document.getElementById(id);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth' });
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50 dark:from-gray-900 dark:to-gray-800 py-16">
      <div className="container mx-auto px-4">
        <div className="max-w-7xl mx-auto">
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
            {/* Main Content */}
            <div className="lg:col-span-3 order-2 lg:order-1">
              <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-8">
                <div className="prose prose-lg dark:prose-invert max-w-none">
                  <ReactMarkdown
                    components={{
                      h1: ({ ...props }) => {
                        const text = props.children?.toString() || '';
                        const id = text.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-');
                        return <h1 id={id} className="text-4xl font-bold mb-6 text-gray-900 dark:text-white" {...props} />;
                      },
                      h2: ({ ...props }) => {
                        const text = props.children?.toString() || '';
                        const id = text.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-');
                        return <h2 id={id} className="text-3xl font-bold mt-8 mb-4 text-gray-900 dark:text-white" {...props} />;
                      },
                      h3: ({ ...props }) => {
                        const text = props.children?.toString() || '';
                        const id = text.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-');
                        return <h3 id={id} className="text-2xl font-semibold mt-6 mb-3 text-gray-900 dark:text-white" {...props} />;
                      },
                      h4: ({ ...props }) => {
                        const text = props.children?.toString() || '';
                        const id = text.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-');
                        return <h4 id={id} className="text-xl font-semibold mt-4 mb-2 text-gray-900 dark:text-white" {...props} />;
                      },
                      p: ({ ...props }) => <p className="mb-4 text-gray-700 dark:text-gray-300" {...props} />,
                      ul: ({ ...props }) => <ul className="list-disc list-inside mb-4 text-gray-700 dark:text-gray-300" {...props} />,
                      ol: ({ ...props }) => <ol className="list-decimal list-inside mb-4 text-gray-700 dark:text-gray-300" {...props} />,
                      li: ({ ...props }) => <li className="mb-2" {...props} />,
                      strong: ({ ...props }) => <strong className="font-semibold text-gray-900 dark:text-white" {...props} />,
                      a: ({ ...props }) => <a className="text-blue-600 dark:text-blue-400 hover:underline" {...props} />,
                    }}
                  >
                    {content}
                  </ReactMarkdown>
                </div>
              </div>
            </div>

            {/* Table of Contents Sidebar */}
            <div className="lg:col-span-1 order-1 lg:order-2">
              <div className="lg:sticky lg:top-24 bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
                <h3 className="text-lg font-bold mb-4 text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '目录' : 'Table of Contents'}
                </h3>
                {headings.length > 0 ? (
                  <nav className="space-y-2 max-h-[calc(100vh-200px)] overflow-y-auto">
                    {headings.map((heading, index) => (
                      <button
                        key={`${heading.id}-${index}`}
                        onClick={() => scrollToHeading(heading.id)}
                        className={`block text-left w-full hover:text-blue-600 dark:hover:text-blue-400 transition-colors ${
                          heading.level === 1 ? 'font-bold text-base' : 
                          heading.level === 2 ? 'font-semibold text-sm pl-2' :
                          heading.level === 3 ? 'text-sm pl-4' :
                          'text-xs pl-6'
                        } text-gray-700 dark:text-gray-300`}
                      >
                        {heading.text}
                      </button>
                    ))}
                  </nav>
                ) : (
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    {language === 'zh-CN' ? '加载中...' : 'Loading...'}
                  </p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default TermsOfService;
